import { useState, useEffect } from 'react';
import { View, Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { Form, Input, Button, Picker, Toast } from '@nutui/nutui-react-taro';
import HeadBar from '@/components/HeadBar';
import { findpasswordApi, searchUserRandomQuestionApi } from '@/api/handleUserAccount';
import './FindPassword.scss';

const FindPassword = () => {
  const [formState, setFormState] = useState({
    userName: '',
    phone: '',
    question: '',
    answer: '',
  });
  const [isForgetUserName, setIsForgetUserName] = useState(false);
  const [isPhoneFill, setIsPhoneFill] = useState(false);
  const [isFindPassword, setIsFindPassword] = useState(false);
  const [userPassword, setUserPassword] = useState('');
  const [questionId, setQuestionId] = useState('');
  const [randomQuestionList, setRandomQuestionList] = useState([]);
  const [showToast, setShowToast] = useState({ show: false, msg: '', type: 'text' });

  const checkPhone = (value) => {
    const regex = /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/;
    return regex.test(value);
  };

  const showNutToast = (msg, type = 'text') => {
    setShowToast({ show: true, msg, type });
    setTimeout(() => setShowToast({ show: false, msg: '', type: 'text' }), 2000);
  };

  const questionSelectChange = (val) => {
    const selected = randomQuestionList[val[0]];
    setFormState({ ...formState, question: selected.value });
    setQuestionId(selected.id);
  };

  const forgetUserName = () => {
    setIsForgetUserName(!isForgetUserName);
    setFormState({
      userName: '',
      phone: '',
      question: '',
      answer: '',
    });
  };

  const fillPhoneNextOrPre = async (param) => {
    if (param) {
      if (!formState.phone || !checkPhone(formState.phone)) {
        showNutToast('请输入合法手机号', 'warn');
        return;
      }
      try {
        const params = { phone: formState.phone };
        const resQuestionList = await searchUserRandomQuestionApi(params);
        if (resQuestionList?.length > 0) {
          setRandomQuestionList(resQuestionList.map(item => ({
            id: item.id,
            value: item.question,
          })));
          setIsPhoneFill(param);
        }
      } catch (error) {
        console.error('Error fetching questions:', error);
        showNutToast('获取问题失败', 'fail');
      }
    } else {
      setIsPhoneFill(param);
    }
  };

  const findPassword = async () => {
    if (!formState.phone || !checkPhone(formState.phone)) {
      showNutToast('请输入合法手机号', 'warn');
      return;
    }

    try {
      let params;
      if (isForgetUserName) {
        if (!formState.question || !formState.answer) {
          showNutToast('请填写完整信息', 'warn');
          return;
        }
        params = {
          phone: formState.phone,
          randomQuestion: [
            {
              id: questionId,
              question: formState.question,
              answer: formState.answer,
            },
          ],
        };
      } else {
        if (!formState.userName) {
          showNutToast('请输入用户名', 'warn');
          return;
        }
        params = {
          userName: formState.userName,
          phone: formState.phone,
        };
      }

      const res = await findpasswordApi(params);
      if (res && res.password) {
        setUserPassword(res.password);
        setIsFindPassword(true);
      } else {
        showNutToast('找回密码失败', 'fail');
      }
    } catch (error) {
      console.error('Error finding password:', error);
      showNutToast('找回密码失败', 'fail');
    }
  };

  const goLogin = () => {
    Taro.redirectTo({ url: '/pages/login/login' });
  };

  return (
    <View className='findPassword'>
      <Toast visible={showToast.show} msg={showToast.msg} type={showToast.type} />
      <HeadBar title='找回密码' />
      {!isFindPassword ? (
        <Form>
          {!isForgetUserName && (
            <Input
              label='用户名'
              placeholder='请输入用户名'
              value={formState.userName}
              onChange={value => setFormState({ ...formState, userName: value })}
            />
          )}
          <Input
            label='手机号'
            placeholder='请输入手机号'
            value={formState.phone}
            onChange={value => setFormState({ ...formState, phone: value })}
          />
          {isForgetUserName && isPhoneFill && (
            <>
              <Picker
                options={randomQuestionList.map(item => item.value)}
                onConfirm={val => questionSelectChange(val)}
              >
                {formState.question || '请选择问题'}
              </Picker>
              <Input
                label='答案'
                placeholder='请输入答案'
                value={formState.answer}
                onChange={value => setFormState({ ...formState, answer: value })}
              />
            </>
          )}
        </Form>
      ) : (
        <View className='password-result'>
          <Text>以下为您的密码，请妥善保存</Text>
          <Text className='password'>{userPassword}</Text>
          <Text className='link' onClick={goLogin}>返回登录页</Text>
        </View>
      )}

      {!isFindPassword && (
        <View className='handleBtn'>
          {isForgetUserName && isPhoneFill && (
            <Button onClick={() => fillPhoneNextOrPre(false)}>上一步</Button>
          )}
          {!isForgetUserName && (
            <Button onClick={forgetUserName}>忘记用户名</Button>
          )}
          {isForgetUserName && !isPhoneFill && (
            <Button onClick={() => fillPhoneNextOrPre(true)}>下一步</Button>
          )}
          <Button type='primary' onClick={findPassword}>找回</Button>
        </View>
      )}
    </View>
  );
};

export default FindPassword;